package com.easyskool.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.easyskool.constants.CommonConstants;
import com.easyskool.hibernate.model.Schools;
import com.easyskool.hibernate.model.accessGroupPOJO;
import com.easyskool.services.core.UserAuthenticationService;
import com.easyskool.utilfunction.NullObjects;
import com.easyskool.utilfunction.UtilFunctions;

@SuppressWarnings("unchecked")
public class RestFilter implements Filter {

	public void init(FilterConfig config) throws ServletException {
		// If you have any <init-param> in web.xml, then you could get them
		// here by config.getInitParameter("name") and assign it as field.
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		if(!CommonConstants.dev)
		{
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession(true);
		String agCode = (String) session.getAttribute("accessGroup");
		String user = (String) session.getAttribute(CommonConstants.USERCODE);
		
		String path = req.getPathInfo();
		System.out.println("path in RestFilter is " + path);
		if (path.contains("/userauthservice")) {
			chain.doFilter(request, response);
			return;
		}

		System.out.println(path + " :is the path " + req.getContextPath() + " "
				+ req.getMethod() + " ");
		System.out.println("AG CODE "+agCode);
		if (agCode == null || "".equals(agCode)) {
			System.out.println("the session is not set");
			res.sendError(401);
			return;
		}
		boolean isAllowed = UtilFunctions.verifyPathfromDB(path, agCode);
		if (isAllowed) {
			System.out.println("the user:"+user+" is allowed");
			chain.doFilter(request, response);
		} else {
			System.out.println("the user:"+ user+" is not allowed");
			res.sendError(401);
		}
		}
		else
		{
			HttpServletRequest req = (HttpServletRequest) request;
			HttpSession session = req.getSession(true);
			
			new CommonConstants();
			session.setAttribute(CommonConstants.ACCESS_GROUPS, CommonConstants.ACCESSGROUP_DEV);
			session.setAttribute(CommonConstants.USERCODE,CommonConstants.USERCODE_DEV);
			session.setAttribute(CommonConstants.SCHOOL_CODE, CommonConstants.SCHOOL_DEV);
			chain.doFilter(request, response);
		}
	}
	

	@Override
	public void destroy() {
		// If you have assigned any expensive resources as field of
		// this Filter class, then you could clean/close them here.
	}

}
